package com.abel.demo.config.apiversion;

import com.abel.demo.utils.ToolsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.mvc.condition.RequestCondition;

import javax.servlet.http.HttpServletRequest;

/**
 * Author: Abel.lin
 * Date: 2021/6/30 11:20
 * Company: Abel.Studio
 * Description:
 */
@Slf4j
public class ApiCondition implements RequestCondition<ApiCondition> {

    private String version;

    public ApiCondition(String version) {
        this.version = version;
    }

    @Override
    public ApiCondition combine(ApiCondition other) {
        // 选择版本最大的接口
        log.info("3=========>{}, {}", this.version, other.version);
        return ToolsUtil.compareApiVersion(this.version, other.version) >= 0 ? new ApiCondition(this.version) : new ApiCondition(other.version);
    }

    @Override
    public ApiCondition getMatchingCondition(HttpServletRequest request) {
        String version = request.getHeader("api-v");
        log.info("0=========>{}, {}, {}", request.getRequestURI(), version, this.version);
        // 获取所有小于等于版本的接口
        if (ToolsUtil.compareApiVersion(version, this.version) >= 0) {
            return this;
        }

        return null;
    }

    @Override
    public int compareTo(ApiCondition other, HttpServletRequest request) {
        // 获取最大版本对应的接口
        log.info("1=========>{}, {}, {}", request.getRequestURI(), other.version, this.version);
        return ToolsUtil.compareApiVersion(other.version, this.version);
    }
}